<?php
namespace App\DAO;

use Swoole;

class BaseDAO
{
    protected $db_key = 'master';

    protected $model_name;

    protected  $user_key_pre = "";

    function __construct()
    {
        if (!isset($this->model_name)) {
            $this->setDefaultModelName();
        }
    }

    public static function getInstance()
    {
        return Swoole::getInstance()->instance_factory->getInstance(static::class, false);
    }


    public function getClassName()
    {
        return end(explode('\\', static::class));
    }

    //默认值是ID
    public function get($value, $key = '')
    {
        return model($this->model_name, $this->db_key)->get($value, $key)->get();
    }


    public function all()
    {
        return model($this->model_name, $this->db_key)->gets(['order']);
    }


    public function insert($attributes)
    {
        foreach($attributes as $key => $value) {
            if (is_null($value)) {
                unset($attributes[$key]);
            }
        }
        $ret = model($this->model_name, $this->db_key)->put($attributes);
//        $key  = $this->model_name."#".$ret ;
//        Swoole::getInstance()->redis->hMset($key,$attributes);
        return $ret;
    }


    public function set($id,$attributes,$where)
    {
        foreach($attributes as $key => $value) {
            if (is_null($value)) {
                unset($attributes[$key]);
            }
        }
        return model($this->model_name, $this->db_key)->set($id,$attributes,$where);
    }

    public function getModelName()
    {
        return $this->model_name;
    }


    public function getDbKey()
    {
        return $this->db_key;
    }


    private function setDefaultModelName()
    {
        $full = static::class;
        $info = explode("\\", $full);
        $model_name = end($info);
        if (strrchr($model_name, 'DAO')) {
            $model_name = substr($model_name, 0, strlen($model_name) - 3);
        }
        $this->model_name = $model_name;
    }
}
